package controllers;

import bill.Bill;
import bill.WithdrawalsBill;
import com.github.binarywang.wxpay.bean.request.WxEntPayRequest;
import com.github.binarywang.wxpay.bean.result.WxEntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.gson.Gson;
import enums.BillOutStatus;
import enums.BillStatus;
import enums.DistributeStatus;
import models.constants.SuccessStatus;
import models.helper.WxMpHelper;
import models.merchant.Merchant;
import models.pay.WeixinPayHelper;
import models.weixin.WebUser;
import order.DeliveryItem;
import play.Logger;
import play.mvc.Controller;
import play.mvc.With;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 财务管理
 * Created by
 */
@With(LoginInCtrl.class)
public class BillCtrl extends Controller {

    public static void index(){
        Merchant merchant = LoginInCtrl.getMerchant();

        Bill bill = null;
        //总金额
        List<Map<String,Object>> sumAmount = Bill.loadAmount(merchant.id,null);
        // 冻结金额
        List<Map<String,Object>> frozenAmount = Bill.loadAmount(merchant.id, BillOutStatus.FROZEN);
        // 正常可以提现金额
        List<Map<String,Object>> normalAmount = Bill.loadAmount(merchant.id, BillOutStatus.NORMAL);
        WebUser webUser = null;
        if(merchant.webUserId != null){
            webUser = WebUser.findById(merchant.webUserId);
        }
      /*  Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("sumAmount",sumAmount.get(0).get("sumAmount"));
        resultMap.put("frozenAmount",frozenAmount.get(0).get("sumAmount"));
        resultMap.put("normalAmount",normalAmount.get(0).get("sumAmount"));*/
        render(merchant,webUser,frozenAmount);
    }
    public static  void frozenBillList(){
        Merchant merchant = LoginInCtrl.getMerchant();
        //           List<Report> reportList = Report.getListByMerchantAndFrozen(merchant);
        List<Bill> listBill = Bill.getBillListByFrozen(merchant,BillOutStatus.FROZEN, BillStatus.IN_AMOUNT);
        render(listBill);
    }

    public static  void  bindingUser(){
        render();
    }

    public static  void  bindingUserByPhone(String searchPhone){
        Logger.info("phone=====  : %s" ,searchPhone);
        Map<String, Object> resultMap = new HashMap<>();
        List<WebUser> webUserList = WebUser.findUserByPhone(searchPhone);
        if(webUserList.size() ==0 ){
            resultMap.put("success", false);

            renderJSON(resultMap);
        }
        resultMap.put("success", true);
        resultMap.put("webUserList", webUserList);
        renderJSON(resultMap);
    }


    public static  void  bindingPhone(Long id){
        Merchant merchant = LoginInCtrl.getMerchant();
        Logger.info("id=====  : %s" ,id);
        Map<String, Object> resultMap = new HashMap<>();
        WebUser webUser = WebUser.findById(id);
//        Merchant newMer = merchant.findMerchantByWebUserId(id);
        if(webUser != null ){
            merchant.webUserId = webUser.id;
            merchant.save();
            resultMap.put("success", true);
        }else{
            resultMap.put("success", false);
        }
        renderJSON(resultMap);
    }


    /**
     * 用户提现
     * @param amount
     */
    public static void withdrawals(Integer amount) {
        Map<String , Object> resultMap = new HashMap<>();
        Merchant merchant = LoginInCtrl.getMerchant();
        WebUser webUser = WebUser.findById(merchant.webUserId);
        // 商户未绑定用户
        if(webUser == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "商户未绑定微信，请先绑定微信");
            renderJSON(resultMap);
        }

        if(merchant.withdrawalsAmount == null || merchant.withdrawalsAmount < 1) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "您的账户余额不足一元 不能提现。");
            renderJSON(resultMap);
        }

        if(amount == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "提现金额不能为空");
            renderJSON(resultMap);
        }

        if(merchant.withdrawalsAmount < amount) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "账户可提现金额不足");
            renderJSON(resultMap);
        }

        WithdrawalsBill withdrawalsBill =  new WithdrawalsBill(merchant , amount).save();
        Logger.info("withdrawalsBill : %s" + new Gson().toJson(withdrawalsBill));
        WxEntPayRequest entpayInfo = WeixinPayHelper.entpayInfo(withdrawalsBill);
        WxPayService wxPayService = WxMpHelper.getWxPayService(webUser);
        try {
            WxEntPayResult wxEntPayResult = wxPayService.entPay(entpayInfo);
            Logger.info("WxEntPayResult : %s" + wxEntPayResult);
            if ("SUCCESS".equals(wxEntPayResult.getResultCode().toUpperCase())
                    && "SUCCESS".equals(wxEntPayResult.getReturnCode().toUpperCase())) {
                Double resultAmount =merchant.withdrawalsAmount-Double.parseDouble(amount.toString());
                merchant.withdrawalsAmount = resultAmount;
                merchant.save();
                WithdrawalsBill newWithdrawalsBill = WithdrawalsBill.findByOrderNumber(withdrawalsBill.billCode);
                newWithdrawalsBill.successStatus = SuccessStatus.SUCCESS;
                newWithdrawalsBill.createAt = new Date();
                newWithdrawalsBill.save();
                resultMap.put("success" , true);
                resultMap.put("msg" , "提现成功，请微信端查看");
                renderJSON(resultMap);
            } else {
                WithdrawalsBill newWithdrawalsBill = WithdrawalsBill.findByOrderNumber(withdrawalsBill.billCode);
                newWithdrawalsBill.successStatus = SuccessStatus.FAIL;
                newWithdrawalsBill.createAt = new Date();
                newWithdrawalsBill.save();
                resultMap.put("success" , true);
                resultMap.put("msg" , "提现失败. 错误代码：" + wxEntPayResult.getErrCode() + "错误描述:" + wxEntPayResult.getErrCodeDes());
                renderJSON(resultMap);
            }
        } catch (WxPayException e) {
            Logger.info("WxEntPayRequest Error : %s" , e.getMessage());
            WithdrawalsBill newWithdrawalsBill = WithdrawalsBill.findByOrderNumber(withdrawalsBill.billCode);
            newWithdrawalsBill.successStatus = SuccessStatus.ABNORMAL;
            newWithdrawalsBill.createAt = new Date();
            newWithdrawalsBill.save();
//             e.printStackTrace();
            resultMap.put("success" , false);
            resultMap.put("msg" , "提现失败，请重试 或联系工作人员");
            renderJSON(resultMap);
        }
    }

    /**
     * 将orderItem 的物流状态，改为用户已接收 ，并更新用户可用体现金额，
     * @param orderItemId
     */
    public static void updateOrderItemDistributeStatus(long orderItemId){
        DeliveryItem deliveryItem = DeliveryItem.findByOrderItemAndDistribute(orderItemId , DistributeStatus.SEND_DISTRIBUTE);

        if(deliveryItem != null){
            deliveryItem.distributeStatus = DistributeStatus.USER_GET;
            deliveryItem.save();

            Bill bill = Bill.getBillByOrderItem(deliveryItem.orderItem);
            if(bill != null){
                Merchant merchant = bill.merchant;
                bill.outStatus = BillOutStatus.NORMAL;
                bill.modifyAt = new Date();
                bill.save();
                if(merchant.frozenAmount == null){
                    merchant.frozenAmount = 0.0d;
                }else if(merchant.frozenAmount > bill.amount || merchant.frozenAmount == bill.amount){
                    merchant.frozenAmount = merchant.frozenAmount-bill.amount;
                }
                merchant.withdrawalsAmount = merchant.withdrawalsAmount == null ? 0.0d : merchant.withdrawalsAmount;
                merchant.withdrawalsAmount  += bill.amount;
                merchant.save();
            }

        }

    }

}
